package com.example.zheng.qq.view;

/**
 * Created by zheng on 17-4-27.暂时还不起效果
 */

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Movie;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.example.zheng.qq.R;


public class MyGifView extends ImageView{

    private long movieStart;

    private Movie movie;

    //此处必须重写该构造方法
    public MyGifView(Context context,AttributeSet attrs) {

        super(context, attrs);
        TypedArray ta = context.obtainStyledAttributes(attrs,
                R.styleable.MyGifView);  //这里用到了attrs.xml里面定义的GifView
        int taCount = ta.length();   //获得属性的个数

        for (int i = 0; i < taCount; i++) {  //处理所有属性，由于我只定义了一个src属性，所以就只处理src属性
            if (R.styleable.MyGifView_auto_play == ta.getIndex(i)) {
                boolean auto_play = ta.getBoolean(R.styleable.MyGifView_auto_play,false); //这里的参数是前面的GifView + _ + src链接起来
                Log.d("dd", auto_play + "");
                if (!auto_play) {
                    setSrc();  //对应的函数，即在xml里面设置了src，相应的处理就会在setSrc函数里面进行
                }
            }
            ta.recycle();
        }
    }






    private void setSrc() {
        movie=Movie.decodeStream(getResources().openRawResource(R.drawable.qqbackground));
        Log.d("12","加载gif图片");
    }

//以文件流（InputStream）读取进gif图片资源







    @Override

    protected void onDraw(Canvas canvas) {

        long curTime=android.os.SystemClock.uptimeMillis();
//        long curTime=System.currentTimeMillis();

//第一次播放

        if (movieStart == 0) {

            movieStart = curTime;

        }

        if (movie != null) {

            int duraction = movie.duration();
            if(duraction==0){
                duraction=1000;
            }
            Log.d("12","加载gif图片中");
            int relTime = (int) ((curTime-movieStart)%duraction);
//            int relTime=1;
            movie.setTime(relTime);
            Log.d("12","加载gif图片中");
            movie.draw(canvas,getWidth() - movie.width(),  //播放（即绘画）
                    getHeight() -movie.height());

//强制重绘

            invalidate();

        }
        Log.d("12","加载gif图片成功");
        super.onDraw(canvas);

    }

}

